//
//  playLayer.m
//  zhuan
//
//  Created by zhao ys on 5/27/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "playLayer.h"
#import "GameLogic.h"
#import "pauseLayer.h"
#import "SoundManager.h"
#import "HelloWorldLayer.h"
#import "scoreLayer.h"
#import "levelupLayer.h"
#import "GameCenter.h"

int offset_x = 52, offset_y = 84;
int grid_width = 40, grid_height = 40;


@implementation playLayer

+(CCScene *) scene {
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	playLayer *layer = [playLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

-(CCSprite*) CreateSpriteAt:(CGPoint)pt name:(NSString*)name {
	CCSpriteFrame * frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
	if (frame == nil) {
		return nil;
	}
	
	CCSprite * sprite = [CCSprite spriteWithSpriteFrame:frame];
	sprite.position = pt;
	return sprite;
}

-(CGPoint) positionOf:(int)x Y:(int)y {
	return ccp(offset_x + (x + 0.5) * grid_width, offset_y + (y+0.5) * grid_height);	
}

#if 0
-(void)CreateButton:(int)type X:(int)x Y:(int)y {
	GameLogic *logic = [GameLogic sharedGameLogic];
	
	CGPoint pt = [self positionOf:x Y:y];

	NSString * frame_name = [buttons_frame_name_ objectAtIndex:type - 1];
	NSNumber * key = [NSNumber numberWithInt:type];
	if ([buttons_free_ objectForKey:key] == nil) {
		[buttons_free_ setObject:[[NSMutableArray array] retain] forKey:key];
	}
	
	NSMutableArray * array = [buttons_free_ objectForKey:key];
	for (int i = 0; i < array.count; i++) {
		CCSprite * sprite = [array objectAtIndex:i];
		if (sprite.tag < 0) {
			sprite.position = pt;
			sprite.visible = YES;
			sprite.tag = (y * logic.col + x) * 1000 + type;
			[array removeObjectAtIndex:i];
			return;
		}
	}
	
	NSLog(@"CreateButton %d@(%d,%d)\n", type, x, y);
	CCSprite * sprite = [self CreateSpriteAt:pt name:frame_name];
	sprite.position = pt;
	sprite.visible = YES;
	[batchNode_ addChild:sprite z:0 tag:(y * logic.col + x) * 1000 + type];
	
	sprite.scale = 0.1;
	[sprite runAction:[CCScaleTo actionWithDuration:0.5 scale:1]];
}
#endif

-(void)CreateButton:(int)type X:(int)x Y:(int)y {
	GameLogic *logic = [GameLogic sharedGameLogic];
	
	CGPoint pt = [self positionOf:x Y:y];
	
	NSString * frame_name = @"dkz_button_disable_03.png";
	if (type > 0 && type <= buttons_frame_name_.count) {
		frame_name = [buttons_frame_name_ objectAtIndex:type - 1];
	}
	
	NSMutableArray * array = nil;
	if (type > 0) {
		NSNumber * key = [NSNumber numberWithInt:type];
		if ([buttons_free_ objectForKey:key] == nil) {
			[buttons_free_ setObject:[[NSMutableArray array] retain] forKey:key];
		}
	    array = [buttons_free_ objectForKey:key];
	
		for (int i = 0; i < array.count; i++) {
			CCSprite * sprite = [array objectAtIndex:i];
			if (sprite.tag < 0) {
				sprite.position = pt;
				sprite.visible = YES;
			
				sprite.rotation = 0;
				sprite.scale = 0.1;
				[sprite runAction:[CCScaleTo actionWithDuration:0.5 scale:1]];
				
				sprite.tag = (y * logic.col + x) * 1000 + type;
				[array removeObjectAtIndex:i];
				return;
			}
		}
	}
	
	NSLog(@"CreateButton %d@(%d,%d)\n", type, x, y);
	CCSprite * sprite = [self CreateSpriteAt:pt name:frame_name];
	sprite.position = pt;
	sprite.visible = YES;
	
	if (type <= 0) {
		[batchNode_ addChild:sprite];
	} else {
		[batchNode_ addChild:sprite z:0 tag:(y * logic.col + x) * 1000 + type];
	}
	
	sprite.scale = 0.1;
	[sprite runAction:[CCScaleTo actionWithDuration:0.5 scale:1]];
}

-(void) AddTime {
    GameLogic * logic = [GameLogic sharedGameLogic];
    float t = logic.time_left;
    [logic addTime:t];
}

-(int) LoadGameOfTheme:(NSString*) theme {
	CGSize size = [[CCDirector sharedDirector] winSize];

	NSString *path = [CCFileUtils fullPathFromRelativePath:@"game_config.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
	
	if (dict == nil) {
		return -1;
	}

	NSDictionary * dictThemes = [dict objectForKey:@"theme"];
	if (theme == nil) {
		theme = [dictThemes objectForKey:@"default"];
		if (theme == nil){
			return -1;
		}
	}
	
	NSDictionary * dictTheme = [dictThemes objectForKey:theme];
	if (dictTheme == nil) {
		return -1;
	}
	
	NSString * plist = [dictTheme objectForKey:@"plist"];
	NSString * png = [dictTheme objectForKey:@"png"];
	if (plist == nil || png == nil) {
		return -1;
	}
	
	[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:plist];
	batchNode_ = [CCSpriteBatchNode batchNodeWithFile:png];
	
	
	//load back ground
	NSString * background = [dictTheme objectForKey:@"background"];
	CCSpriteFrame * bgframe = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:background];
	CCSprite * bg = [CCSprite spriteWithSpriteFrame:bgframe];
	bg.position = ccp(size.width / 2, size.height / 2);
	[self addChild:bg z:-1];
	
	//pause
	CCSprite * pause_sprite = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_pause.png"]];
	CCSprite * pause_sprite_s = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_pause.png"]];

	CCMenuItem * menu_pause = [CCMenuItemSprite itemFromNormalSprite:pause_sprite selectedSprite:pause_sprite_s
														 target:self selector:@selector(OnMenuPause:)];
	//CCMenuItemFont * pause = [CCMenuItemFont itemFromString: @"[pause]" target:self selector:@selector(OnMenuPause:)];
	CGSize pause_size = menu_pause.contentSize;
	menu_pause.position = ccp(size.width - pause_size.width / 2 - 80, size.height - pause_size.height / 2 + 5);
	
	
	//sound
	music_on = [[dict objectForKey:@"music"] boolValue];
	sound_on = [[dict objectForKey:@"sound"] boolValue];
	
	CCSprite * sound_sprite_on = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_sound_on.png"]];
	CCSprite * sound_sprite_on_s = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_sound_on.png"]];
	CCMenuItem * menu_sound_on = [CCMenuItemSprite itemFromNormalSprite:sound_sprite_on selectedSprite:sound_sprite_on_s];

	CCSprite * sound_sprite_off = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_sound_off.png"]];
	CCSprite * sound_sprite_off_s = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_sound_off.png"]];
	CCMenuItem * menu_sound_off = [CCMenuItemSprite itemFromNormalSprite:sound_sprite_off selectedSprite:sound_sprite_off_s];
	
	menu_sound_ = [CCMenuItemToggle itemWithTarget:self selector:@selector(OnMenuSound:) items:menu_sound_off, menu_sound_on, nil];
	CGSize sound_size = menu_sound_.contentSize;
	menu_sound_.position = ccp(size.width - sound_size.width / 2 - 10, size.height - sound_size.height / 2 - 10);
	
	if (tmp_sound_) {
		menu_sound_.selectedIndex = 1;
	} else {
		menu_sound_.selectedIndex = 0;
	}
	CCMenu * menu = [CCMenu menuWithItems:menu_pause, menu_sound_, nil];
	menu.position = ccp(0,0);
	[self addChild:menu];
	
	NSDictionary * position = [dictTheme objectForKey:@"position"];
	
	offset_x = [[position objectForKey:@"x"] intValue];
	offset_y = [[position objectForKey:@"y"] intValue];
	
	//load progress
	CCSpriteFrame * f_c = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_timeline_03.png"];
	progress_l_ = [CCProgressTimer progressWithFile:@"dkz_timeline_01.png"];
	progress_r_ = [CCProgressTimer progressWithFile:@"dkz_timeline_02.png"];
	progress_c_ = [CCSprite spriteWithSpriteFrame:f_c];
	CCSprite * progress_c_l_ = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_timeline_04.png"]];
	CGSize pcSize = progress_c_l_.contentSize;
	progress_c_l_.anchorPoint = ccp(0.5, 1);
	progress_c_l_.position = ccp(5, pcSize.height / 2 + 1);
	progress_c_l_.rotation = 20;
	[progress_c_l_ runAction:[CCRepeatForever actionWithAction:[CCSequence actions:
																[CCEaseInOut actionWithAction:[CCRotateTo actionWithDuration:1.5 angle:-20] rate:2], 
																[CCEaseInOut actionWithAction:[CCRotateTo actionWithDuration:1.5 angle:20] rate:2],
																nil]]];
	[progress_c_ addChild:progress_c_l_];

	CGSize psize = progress_l_.contentSize;
	progress_l_.position = progress_r_.position = ccp(psize.width / 2 + offset_x + 30, size.height - 32);
	progress_c_.position = ccp(progress_l_.position.x + (1 - 0.5) * psize.width - 10, size.height - 32);
	
	[progress_l_ setType:kCCProgressTimerTypeHorizontalBarLR];
	[progress_l_ setPercentage:100.0f];
	
	[progress_r_ setType:kCCProgressTimerTypeHorizontalBarRL];
	[progress_r_ setPercentage:0.0f];
	[self addChild:progress_l_];
	[self addChild:progress_r_];
	[self addChild:progress_c_];
	
	//label_sec_ = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", time_max_] fontName:@"Marker Felt" fontSize:24];
	//[progress_c_ addChild:label_sec_];
	//CGSize csize = progress_c_.contentSize;
	//label_sec_.position = ccp(csize.width / 2 - 10, csize.height / 2);
	
	//load game config
	NSDictionary * grid = [dictTheme objectForKey:@"grid"];
	grid_width = [[grid objectForKey:@"width"] intValue];
	grid_height = [[grid objectForKey:@"height"] intValue];

	GameLogic *logic = [GameLogic sharedGameLogic];
	//TODO:CreateShadowButton
	{
		int x = (23 - logic.col) / 2;
		int y = (15 - logic.row) / 2;
		int width = logic.col;
		int height = logic.row;
		CGRect rect1 = CGRectMake(x, y, width, height);
		CGRect rect2 = CGRectMake(x-1, y-1, width + 2, height + 2);
		for (x = 0; x < 23; x++) {
			for (y = 0; y < 15; y++) {
				CGPoint pt = CGPointMake(x, y);
				if (CGRectContainsPoint(rect1, pt)) {
					continue;
				}
				
				if (CGRectContainsPoint(rect2, pt)) {
					[self CreateButton:-1 X:x Y:y];
				}
			}
		}
	}
	
	offset_x += (23 - logic.col) / 2 *  grid_width;
	offset_y += (15 - logic.row) / 2 * grid_height;

	buttons_frame_name_ = [[NSMutableArray arrayWithArray:[dictTheme objectForKey:@"button"]] retain];
		
	//sprite
	for (int y = 0; y < logic.row; y ++) {
		for(int x = 0; x < logic.col; x++) {
			int val = [logic valueAt:x Y:y];
			if (val <= 0 || val > buttons_frame_name_.count) {
				continue;
			}
			[self CreateButton:val X:x Y:y];
		}
	}
	[self addChild:batchNode_];

	press_animation_ = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_prasscircle.png"]];
	press_animation_.visible = NO;
	[self addChild:press_animation_];

	//path
	NSString * connection = [dictTheme objectForKey:@"connection"]; 
	path_left_time_ = 0;
	pathNode_ = [CCSpriteBatchNode batchNodeWithFile:png];
	for (int i = 0; i < logic.col + logic.row; i++) {
		CCSprite * sprite = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:connection]];
		[pathNode_ addChild:sprite z:0 tag:i];
		sprite.visible = NO;
	}
	[self addChild:pathNode_];
	

	// remove tools
	CCSpriteFrame * bomb_frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_bomb.png"];
	CCMenu * bomb_menu = [CCMenu menuWithItems:nil];
	for (int i = 0; i < remove_tools_; i++) {
		CCSprite * bomb = [CCSprite spriteWithSpriteFrame:bomb_frame];
		CCMenuItem * item = [CCMenuItemSprite itemFromNormalSprite:bomb selectedSprite:nil target:self selector:@selector(OnBomb:)];
		//bomb.tag = 80 + i;
		item.position = ccp(size.width - bomb_frame.rect.size.width * (i + 1), 30);
		[bomb_menu addChild:item];
	}
	
	bomb_menu.position = ccp(0,0);
	
	//[bomb_menu alignItemsHorizontallyWithPadding:0];
	//bomb_menu.position = ccp(size.width - 200, 30);
	[self addChild:bomb_menu];
	return 0;
}


-(void) LoadHelp {
	NSLog(@"playerLayer LoadHelp\n");
	// help
	CGSize size = [[CCDirector sharedDirector] winSize];

	help_ = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_help_01.png"]];
	help_.position = ccp(size.width / 2, size.height / 2);
	color_layer_ = [CCLayerColor layerWithColor:ccc4(0, 0, 0, 150)];
	[self addChild:color_layer_];
	[self addChild:help_];
}


-(void) StartTimer {
	if (running_ && auto_play_on && (timer_ == nil)) {
		timer_ = [NSTimer scheduledTimerWithTimeInterval: 0.5
												  target: self
												selector: @selector(handleTimer:)
												userInfo: nil
												 repeats: YES];

	}
}

-(void) StopTimer {
	if (timer_) {
		[timer_ invalidate];
		timer_ = nil;
	}
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
		NSLog(@"playerLayer init\n");

		
		[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"dkz.plist"];

		// ask director the the window size
		//CGSize size = [[CCDirector sharedDirector] winSize];
		
		running_ = NO;
		done_ = NO;
		tmp_sound_ = YES;
		remove_tools_ = 5;
		removing_ = NO;
		if (sound_on == NO && music_on == NO) {
			tmp_sound_ = NO;
		}
		
		timer_ = nil;

		buttons_free_ = [[NSMutableDictionary dictionary] retain];
		
		[self LoadGameOfTheme:nil];

		//hint
		CCSprite * hint = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_prasscircle.png"]]; 
		//[CCSprite spriteWithFile:@"hint.png"];
		hint.visible = NO;
		[self addChild:hint z:2 tag:999];
		hint_left_time_ = hint_time_;

		score_cur_ = 0;
		time_cost_ = 0;
		addition_score_ = 0;
		
		
		//button_score_ = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"dkz_unprass_01.png"]];
		//button_score_.position =  ccp(size.width / 4 , 30);
		//[self addChild: button_score_];

		//score
		label_score_ = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"score: %d", score_] fontName:@"Marker Felt" fontSize:32];
		//CGSize bsSize = button_score_.contentSize;
		label_score_.position = ccp(370, 30);
		label_score_.color = ccc3(243, 189, 69);
		[self addChild:label_score_];
		
		
		//level
		CCLabelTTF * label_level = nil;
		if ([GameLogic IsScoreMode]) {
			label_level = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"level: %d", cur_level_] fontName:@"Marker Felt" fontSize:32];
		} else if ([GameLogic IsClassicMode]) {
			label_level = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"challenge", cur_level_] fontName:@"Marker Felt" fontSize:32];
		} else {
			label_level = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"endless", cur_level_] fontName:@"Marker Felt" fontSize:32];
		}
		label_level.position = ccp(180, 30);
		label_level.color = ccc3(243, 189, 69);
		[self addChild:label_level];
		
		self.isTouchEnabled = YES;
        
        GameLogic * logic = [GameLogic sharedGameLogic];
        
		levelup_left_time_ = 0;
		//time_left_ = logic.time_left;
		[self scheduleUpdate];
		
		if (score_ == 0) {
			[self LoadHelp];
		} else {
			help_ = nil;
			color_layer_ = nil;
			running_ = YES;
			[self StartTimer];
		}
		
		logic.delegate = self;		
	}
	return self;
}




- (void) handleTimer: (NSTimer *) timer
{
	//在这里进行处理
	GameLogic* logic = [GameLogic sharedGameLogic];
	
	int pos = [logic nextStep];
	if (pos >= 0) {
		int x = pos % logic.col;
		int y = pos / logic.col;
		
		CGPoint pt = [self positionOf:x Y:y];
		[self UserTouch:pt];
	} else {		
		NSLog(@"stop timer\n");
		[timer_ invalidate];
		timer_ = nil;
	}
}

-(void) OnHelpClose {
	[self removeChild:help_ cleanup:YES];
	[self removeChild:color_layer_ cleanup:YES];
	color_layer_ = nil;
	help_ = nil;
	running_ = YES;

	[self StartTimer];
}

-(void) OnMenuPause:(id)sender {
	if (sound_on) [[SoundManager sharedManager] play:@"enter" loops:1];
	
	/*
	[(CCNode*)sender runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.1 scale:0.9],
								[CCCallFunc actionWithTarget:self selector:@selector(pause)],
								[CCScaleTo actionWithDuration:0.1 scale:1], nil]];
	 */
	[self pause];
}

-(void) OnMenuSound:(id)sender {		
	//[(CCNode*)sender runAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.3 scale:0.9], [CCScaleTo actionWithDuration:0.1 scale:1], nil]];
	tmp_sound_ = !tmp_sound_;
	if (tmp_sound_ == NO) {
		[[SoundManager sharedManager] stop:@"drop"];
		[[SoundManager sharedManager] stop:@"background"];
	}
	
	if (tmp_sound_) {
		menu_sound_.selectedIndex = 1;
		if (music_on) {
			[[SoundManager sharedManager] play:@"background" loops:-1];
		}
	} else {
		menu_sound_.selectedIndex = 0;
	}
}

-(void)OnBomb:(id)sender {
	if(remove_tools_ > 0) {
		removing_ = YES;
		using_bomb_.opacity = 255;
		[using_bomb_ stopAllActions];
		using_bomb_ = (CCSprite*)sender;
		[using_bomb_ runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCFadeIn actionWithDuration:0.5], [CCFadeOut actionWithDuration:0.5], nil]]];
//		[self.parent removeChild:sender cleanup:YES];
	}
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {
	}
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {
	}	
}


-(void) onEnter {
	NSLog(@"OnEnter");
	[super onEnter];
	
	if (sound_on == NO && music_on == NO) {
		tmp_sound_ = NO;
	}
	
	if (tmp_sound_) {
		menu_sound_.selectedIndex = 1;
		//[[SoundManager sharedManager] stop:@"background_menu"];
		if (music_on) {
			[[SoundManager sharedManager] play:@"background_menu" loops:-1];
		}
	} else {
		menu_sound_.selectedIndex = 0;
	}
	
	[self StartTimer];
}

-(CCScene*) CreateOnTopScene:(CCLayer*) layer {
	//button_score_.visible = NO;
	// 1. 一个 CCRenderTexture 用以存储当前场景(你就是要在这上面弹出界面)的界面
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	
	CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
	[renderTexture begin];
	[self visit];
	[renderTexture end];
	[renderTexture setPosition:ccp(winSize.width/2, winSize.height/2)];
	
	//button_score_.visible = YES;
	//2. pauseScene 是要弹出的界面场景，看起来还有上一个界面，实际上已经切换了一个场景
	CCScene* newScene = [CCScene node];
	// 3. 一个 CCLayerColor/CCColorLayer （这两个一样） 用以在上一个界面覆盖一层, 实现暗灰效果
	CCLayerColor * colorLayer = [CCLayerColor layerWithColor:ccc4(0, 0, 0, 150)];
	// pauseScene 的组成：从底层向外层： 上一个界面截图，暗灰效果层, 新的弹出菜单层。
	[newScene addChild:renderTexture];
	[newScene addChild:colorLayer];
	[newScene addChild:layer];
	NSLog(@"CreateOnTopScene %p[%d] %p[%d] %p[%d]\n", 
		  renderTexture, [renderTexture retainCount],
		  colorLayer, [colorLayer retainCount],
		  layer, [layer retainCount]);	
	return newScene;
}

-(void) SwitchToLevelUpLayer {
	[self StopTimer];

	[[GameLogic sharedGameLogic] setDelegate:nil];
	NSLog(@"playerLayer SwitchToLevelUpLayer\n");
	[[CCDirector sharedDirector] replaceScene:[self  CreateOnTopScene:[levelupLayer node]]];
}

-(void) SwitchToFinishedScene {
	[self StopTimer];

	[[GameLogic sharedGameLogic] setDelegate:nil];
	NSLog(@"playerLayer SwitchToFinishedScene\n");
	[[CCDirector sharedDirector] replaceScene:[self  CreateOnTopScene:[scoreLayer node]]];
}

-(void) SwitchToPauseScene {
	[self StopTimer];
	
	[[GameLogic sharedGameLogic] setDelegate:nil];
	NSLog(@"playerLayer SwitchToPauseScene\n");
	[[CCDirector sharedDirector] pushScene:[self  CreateOnTopScene:[pauseLayer node]]];
}

-(void) pause {
	[self SwitchToPauseScene];
	
#if 0
	//pause_ = YES;
	//[[CCDirector sharedDirector] pause];
	
	// 1. 一个 CCRenderTexture 用以存储当前场景(你就是要在这上面弹出界面)的界面
	CGSize winSize = [[CCDirector sharedDirector] winSize];
	CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];
	[renderTexture begin];
	[self visit];
	[renderTexture end];
	[renderTexture setPosition:ccp(winSize.width/2, winSize.height/2)];
	
	//2. pauseScene 是要弹出的界面场景，看起来还有上一个界面，实际上已经切换了一个场景
	CCScene* pauseScene = [CCScene node];
	//3. 一个 CCLayerColor/CCColorLayer （这两个一样） 用以在上一个界面覆盖一层, 实现暗灰效果
	CCLayerColor* colorLayer = [CCColorLayer layerWithColor:ccc4(0, 0, 0, 200)];
	// pauseScene 的组成：从底层向外层： 上一个界面截图，暗灰效果层, 新的弹出菜单层。
	[pauseScene addChild:renderTexture];
	[pauseScene addChild:colorLayer];
	[pauseScene addChild:[pauseLayer node]];
	// 4. 直接 push 过去吧，方便存储当前场景状态之类的
	[[CCDirector sharedDirector] pushScene:pauseScene];	
	
	[[SoundManager sharedManager] stop:@"background"];
#endif
}


/*
-(void) LevelUp {
	CCNode * node = [self getChildByTag:23];
	if (node) {
		[self removeChild:node cleanup:YES];
	}
	
	if ([GameLogic IsClassicMode]) {
		[self SwitchToFinishedScene];
	} else {
		[self SwitchToLevelUpLayer];
	}
}
*/

-(void) GameSuccess:(BOOL)success {
	done_ = YES;
	
	CCNode * node = [self getChildByTag:23];
	if (node) {
		[self removeChild:node cleanup:YES];
	}
	
	if (success && [GameLogic IsScoreMode]) {
		[self SwitchToLevelUpLayer];
	} else {
		[self SwitchToFinishedScene];
	}
}

-(BOOL) FinishCheck {
	GameLogic * logic = [GameLogic sharedGameLogic];
	BOOL clear = NO;
	BOOL finished = NO;
	if (logic.left == 0 ) {
		clear = YES;
		finished = YES;
	}
	
	if (![logic haveStep]) {
		if ([GameLogic IsScoreMode]) {
			clear = YES;
			finished = YES;
		} else {
			if (remove_tools_ >= logic.left) {
				clear = YES;
				finished = YES;
			} else {
				clear = NO;
				finished = YES;
			}
		}
	}
	
	if (finished) {
#define LEVELUP_TIME  2	
		levelup_left_time_ = LEVELUP_TIME; 
		addition_score_ = (int)logic.time_left;
		
		if (clear) {
			if (tmp_sound_ && sound_on) [[SoundManager sharedManager] play:@"clear" loops:1];
			
			CCParticleFireworks * emitter = [CCParticleFireworks node];
			[self addChild: emitter z:10 tag:23];
			
			// testing "alpha" blending in premultiplied images
			//	emitter.blendFunc = (ccBlendFunc) {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA};
			emitter.texture = [[CCTextureCache sharedTextureCache] addImage: @"stars.png"];
			emitter.blendAdditive = YES;
			emitter.scale = 10;
			emitter.rotation = 25;
			emitter.position = ccp(100, 0);
			emitter.duration = 1.8;
		} else {
			if (tmp_sound_ && sound_on) [[SoundManager sharedManager] play:@"failed" loops:1];
		}
	}	
	return finished;
}

-(void) UserTouch:(CGPoint)pt {
	int x = (pt.x - offset_x) / grid_width;
	int y = (pt.y - offset_y) / grid_height;
	GameLogic * logic = [GameLogic sharedGameLogic];
	
	if (x < 0 || x >= logic.col ||
		y < 0 || y >= logic.row) {
		if (removing_) {
			removing_ = NO;
			[using_bomb_ stopAllActions];
			using_bomb_.opacity = 255;
		}
		return;
	}
	
	if (removing_) {
		int tag = [[GameLogic sharedGameLogic] remove:x Y:y];
		removing_ = NO;
		[using_bomb_ stopAllActions];
		using_bomb_.opacity = 255;
		if(tag > 0) {
			remove_tools_ --;
			
			
			CCSprite * sprite = (CCSprite*)[batchNode_ getChildByTag:tag];
			
			[[SoundManager sharedManager] play:@"throw" loops:1];
			[using_bomb_ runAction:[CCSequence actions:[CCJumpTo actionWithDuration:0.3 position:sprite.position height:200 jumps:1],
									[CCCallFuncND actionWithTarget:self selector:@selector(OnBombDone:data:) data:sprite], nil]];
			
			using_bomb_ = nil;
			sprite.tag = -(sprite.tag % 1000);
			
			if ([self FinishCheck]) {
				return;
			}
			
		}
		return;
	}
	
	NSMutableArray * array = [[GameLogic sharedGameLogic] hit:x Y:y];
	if (array == nil) {
		return;
	}
	
	//iHit += array.count;
	if (array.count  == 0) {
        [logic addTime:-time_dec_];
		if (sound_on && tmp_sound_) {
			[[SoundManager sharedManager] stop:@"lock"];
			[[SoundManager sharedManager] play:@"lock" loops:1];
		}
		return;
	}
	
	CGPoint pt_grid_center =  [self positionOf:x Y:y];
	press_animation_.position = pt_grid_center;
	[press_animation_ stopAllActions];
	press_animation_.visible = TRUE;
	press_animation_.opacity = 100;
	press_animation_.scale = 1.0f;
	[press_animation_ runAction:[CCScaleTo actionWithDuration:0.5 scale:2.0f]];
	[press_animation_ runAction:[CCFadeTo actionWithDuration:0.5 opacity:0]];
	
	path_left_time_ = 0.5;
	for (int i = 0; i < logic.col + logic.row; i++) {
		CCNode * sprite = [pathNode_ getChildByTag:i];
		sprite.visible = NO;
	}
	for (NSNumber * n in array) {
		int button_value = [n intValue];
		CCSprite * sprite = (CCSprite*)[batchNode_ getChildByTag:button_value];
		int offset = 100;
		if (sprite.position.x < pt.x) {
			offset = -100;
		}
		
		int button_pos = button_value / 1000;
		int button_type = button_value % 1000;
		
		NSMutableArray* pathArray = [logic pathOf:x Y:y  dest:button_pos];
		
		for (NSNumber * n_ in pathArray) {
			int pos = [n_ intValue];
			int x_ = pos % logic.col;
			int y_ = pos / logic.col;
			
			int tag = x_;
			if ( x_ == x && y_ != y) {
				tag = logic.col + y_;
			} 
			CCNode * node = [pathNode_ getChildByTag:tag];
			//NSLog(@"(%d,%d), tag:%d node:%d\n", x_, y_, tag, node);
			node.position = ccp((x_+0.5)*grid_width + offset_x, (y_+0.5)*grid_height + offset_y);
			node.visible = YES;
		}
		[batchNode_ reorderChild:sprite z:1];
		
		/*
		 CCParticleSystemQuad * emitter = [CCParticleSystemQuad particleWithFile:@"LavaFlow.plist"];
		 //CCParticleSystemQuad * emitter = [CCParticleSystemQuad particleWithFile:@"BurstPipe.plist"];
		 emitter.position = sprite.position;
		 emitter.duration = 0.4;
		 emitter.scale = 0.2;
		 [self addChild:emitter];
		 */
		
		CCRotateBy * r = [CCRotateBy actionWithDuration: 0.8 angle:(float) 180];
		CCJumpTo * j = [CCJumpTo actionWithDuration:0.8 position:ccp(sprite.position.x + offset, -20) height:200 jumps:1];
		[sprite runAction:j];
		[sprite runAction:r];
		sprite.tag = -(sprite.tag % 1000);
		
		NSNumber * key = [NSNumber numberWithInt:button_type];
		if ([buttons_free_ objectForKey:key] == nil) {
			[buttons_free_ setObject:[[NSMutableArray array] retain] forKey:key];
		}
		
		NSMutableArray * array = [buttons_free_ objectForKey:key];
		[array addObject:sprite];
		
		score_ ++;
		score_cur_ ++;
	}
	
	if (array.count > 0) {
		if (tmp_sound_ && sound_on) {
			[[SoundManager sharedManager] stop:@"drop"];
			[[SoundManager sharedManager] play:@"drop" loops:1];
		}
	}
	
    [logic addTime:add[array.count-1]];
	
	hint_left_time_ = hint_time_;
	CCNode * hint = [self getChildByTag:999];
	hint.visible = NO;
	
	[label_score_ setString:[NSString stringWithFormat:@"score: %d", score_]];		
	
	
	[self FinishCheck];
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	if (done_ ) {
		return;
	}
	
	if(!running_) {
		[self OnHelpClose];
		return;
	}
	
	if (levelup_left_time_ > 0) {
		return;
	}
	
	for (int i = 0; i < 1; i++) {
	//for (UITouch * touch in touches) {
		UITouch * touch = [touches anyObject];
		CGPoint touchLocation = [touch locationInView: [touch view]];
		touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
		CGPoint pt = [self convertToNodeSpace:touchLocation];
	
		[self UserTouch:pt];
	}
}

-(void) OnBombDone:(id)node data:(void*)data {
	CCSprite * sprite = (CCSprite *) data;
	sprite.visible = NO;
	
	CCNode * bomb = (CCNode *)node;
	bomb.visible = NO;
	bomb.position = ccp(-1000, -1000);
	
	[[SoundManager sharedManager] play:@"bomb" loops:1];

	CCParticleSystemQuad * emitter = [CCParticleSystemQuad particleWithFile:@"ExplodingRing.plist"];
	emitter.position = sprite.position;
	emitter.autoRemoveOnFinish = YES;
	[self addChild:emitter z:10];
}

- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch * touch in touches) {		
	}
}

-(void) update:(ccTime)dt {
	if(!running_) {
		return;
	}
	
	GameLogic * logic = [GameLogic sharedGameLogic];
	if (path_left_time_ > 0) {
		path_left_time_ -= dt;
		if (path_left_time_ <= 0) {
			path_left_time_ = 0;
			for (int i = 0; i < logic.col + logic.row; i++) {
				CCNode * sprite = [pathNode_ getChildByTag:i];
				sprite.visible = NO;
			}
		}
	}

	if (levelup_left_time_ > 0) {
		if(levelup_left_time_ > 0) {
			levelup_left_time_ -= dt;
		} 
		
		int cur_score = score_ + addition_score_ * (1.0f - levelup_left_time_ / LEVELUP_TIME);
		if (cur_score > score_ + addition_score_) {
			cur_score = score_ + addition_score_;
		}
        
		int cur_time_left = logic.time_left * (levelup_left_time_ / LEVELUP_TIME);
		float percent = cur_time_left * 100 / time_max_;
		[progress_l_ setPercentage: percent];
		[progress_r_ setPercentage: 100 - percent];
		CGSize psize = progress_l_.contentSize;
		progress_c_.position = ccp(progress_l_.position.x + (percent / 100.0 - 0.5) * psize.width - 10, progress_c_.position.y);
		
		[label_score_ setString:[NSString stringWithFormat:@"score: %d", cur_score]];
		if (levelup_left_time_ <= 0) {
			levelup_left_time_ = 0;
			score_ += addition_score_;
            
            [logic addTime:-100000];
			
			if ([GameLogic IsScoreMode]) {
				[self GameSuccess:YES];
			} else {
				[self GameSuccess:(logic.left == 0)];
			}
//			[self LevelUp];
		}
		return;
	} 
	
	if (done_) {
		return;
	}
	
	time_cost_ += dt;

	if (logic.time_left > 0) {
        [logic addTime:-dt];
		float percent = logic.time_left * 100 / time_max_;
		[progress_l_ setPercentage: percent];
		[progress_r_ setPercentage: 100 - percent];
		CGSize psize = progress_l_.contentSize;
		progress_c_.position = ccp(progress_l_.position.x + (percent / 100.0 - 0.5) * psize.width - 10, progress_c_.position.y);
	}
		
	if (logic.time_left <= 0) {
		if (tmp_sound_ && sound_on) [[SoundManager sharedManager] play:@"failed" loops:1];
		//[self SwitchToFinishedScene];
		[self GameSuccess:NO];
		return;
	}

		
	if (hint_left_time_ > 0) {
		hint_left_time_ -= dt;
		if (hint_left_time_ <= 0) {
			hint_left_time_ = 0;
			CCNode * hint = [self getChildByTag:999];
			int pos = [logic nextStep];
			if (pos >= 0) {
				int x = pos % logic.col;
				int y = pos / logic.col;
				hint.position = ccp((x+0.5)*grid_width + offset_x, (y+0.5)*grid_height + offset_y);
				hint.visible = YES;
				[hint stopAllActions];
				hint.scale = 0.5f;
				[hint runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:1.0 scale:1.0f],
																   [CCScaleTo actionWithDuration:1.0 scale:0.5f], nil]]];
			}
		}
	}
}


// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	NSLog(@"playerLayer dealloc\n");
	[[SoundManager sharedManager] stop:@"background"];
	
	for (NSMutableArray * array in buttons_free_) {
		[array release];
	}
	
	[super dealloc];
}
@end
